package br.com.ds3.controller;

import java.io.File;
import java.util.List;

import org.hibernate.criterion.Order;

import net.sf.jasperreports.engine.JRException;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.interceptor.download.Download;
import br.com.caelum.vraptor.interceptor.download.FileDownload;
import br.com.ds3.annotation.Permission;
import br.com.ds3.dao.EventoDAO;
import br.com.ds3.dao.InscricaoDAO;
import br.com.ds3.model.Evento;
import br.com.ds3.model.Inscricao;
import br.com.ds3.model.Perfil;
import br.com.ds3.relatorio.util.InscricaoDatasource;
import br.com.ds3.relatorio.util.RelatorioUtil;

@Resource
public class RelatorioController {
	private final Result result;
	
	public RelatorioController(Result result) {
		this.result = result;
	}
	
	private String getJasperFile(String jasperFile) {	
		return new File(getClass().getResource("/br/com/ds3/relatorio/jasper").getFile().replaceAll("%20", "\u0020")).getPath() + File.separator + jasperFile;
	}
	
	public void eventoParticipante() {
		List<Evento> eventos = new EventoDAO().pesquisa(null, null);
		result.include("eventos", eventos);
	}
	
	@Get
	@Permission(value = { Perfil.ADMINISTRADOR, Perfil.ATENDENTE })
	public Download geraRelatorioEventoParticipante(Long idEvento) throws JRException {
		EventoDAO eventoDAO = new EventoDAO();
		Evento evento;
		
		if (idEvento != null) {
			evento = eventoDAO.get(idEvento);
		} else {
			evento = null;
		}
		
		List<Inscricao> inscricoes = new InscricaoDAO().pesquisa(null, evento, false, null, Order.asc("e.nome"), Order.asc("p.nome"));
		File file = RelatorioUtil.geraRelatorio(new InscricaoDatasource(inscricoes), getJasperFile("relacaoInscricoes.jasper"));
		
		String filename = "relacaoInscricoes.pdf";
		String contentType = "application/pdf";
		
		return new FileDownload(file, contentType, filename);
	}
}
